﻿using MxWeiXinPF.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.Entities;

namespace MxWeiXinPF.Web.shop
{
    public partial class userbbsadd : MxWeiXinPF.Web.UI.UserPage
    {
        private string action = MXEnums.ActionEnum.Add.ToString();
        public string carturl = "";
        public string indexurl = "";
        protected int page;
        protected int pageSize;
        protected int shopid = 0x27;
        protected int totalCount;
        protected int uid = 0;
        protected MxWeiXinPF.Model.users user_info;
        public string userinfourl = "";
        public string categoryurl = "";

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbRemarks.Value))
            {
                this.Page.ClientScript.RegisterStartupScript(this.Page.ClientScript.GetType(), "myscripts", "<script>alert(\"留言内容不能为空 \");</script>");
            }
            else if (this.hid.Value.Trim().Equals(""))
            {
                if (!this.DoAdd())
                {
                    this.Page.ClientScript.RegisterStartupScript(this.Page.ClientScript.GetType(), "myscripts", "<script>alert(\"保存过程中发生错误\");</script>");
                }
                else
                {
                    this.RptBind("id>0" + this.CombSqlTxt(this.uid), "updatetime desc");
                    this.Page.ClientScript.RegisterStartupScript(this.Page.ClientScript.GetType(), "myscripts", "<script>alert(\"保存成功！\");</script>");
                }
            }
            else if (!this.DoUpdate(int.Parse(this.hid.Value.Trim())))
            {
                this.Page.ClientScript.RegisterStartupScript(this.Page.ClientScript.GetType(), "myscripts", "<script>alert(\"保存过程中发生错误\");</script>");
            }
            else
            {
                this.RptBind("id>0" + this.CombSqlTxt(this.uid), "updatetime desc");
                this.Page.ClientScript.RegisterStartupScript(this.Page.ClientScript.GetType(), "myscripts", "<script>alert(\"保存成功！\");</script>");
            }
        }

        protected string CombSqlTxt(int uid)
        {
            StringBuilder builder = new StringBuilder();
            if (uid > 0)
            {
                builder.Append(" and uid='" + uid + "'");
            }
            return builder.ToString();
        }

        private bool DoAdd()
        {
            bool flag = false;
            MxWeiXinPF.Model.userbbs model = new MxWeiXinPF.Model.userbbs();
            MxWeiXinPF.BLL.userbbs userbbs2 = new MxWeiXinPF.BLL.userbbs();
            model.uid = this.uid;
            model.shopid = this.shopid;
            model.remarks = this.tbRemarks.Value.Trim();
            model.openid = base.openid;
            model.updatetime = DateTime.Now;
            if (this.tbRemarks.Value.Trim().Length > 20)
            {
                model.title = this.tbRemarks.Value.Trim().Substring(1, 20);
            }
            else
            {
                model.title = this.tbRemarks.Value.Trim();
            }
            if (userbbs2.Add(model) > 0)
            {
                SendTemplateMsg("", model);
                flag = true;
            }
            return flag;
        }

        private bool DoUpdate(int id)
        {
            bool flag = false;
            MxWeiXinPF.Model.userbbs model = new MxWeiXinPF.Model.userbbs();
            MxWeiXinPF.BLL.userbbs userbbs2 = new MxWeiXinPF.BLL.userbbs();
            model.uid = this.uid;
            model.shopid = this.shopid;
            model.remarks = this.tbRemarks.Value.Trim();
            model.openid = base.openid;
            model.updatetime = DateTime.Now;
            model.id = id;
            if (this.tbRemarks.Value.Trim().Length > 20)
            {
                model.title = this.tbRemarks.Value.Trim().Substring(1, 20);
            }
            else
            {
                model.title = this.tbRemarks.Value.Trim();
            }
            if (userbbs2.Add(model) > 0)
            {
                SendTemplateMsg("", model);
                flag = true;
            }
            return flag;
        }

        private int GetPageSize(int _default_size)
        {
            int num;
            if (int.TryParse(Utils.GetCookie("userbbs"), out num) && (num > 0))
            {
                return num;
            }
            return _default_size;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                base.wid = MyCommFun.RequestInt("wid");
                base.openid = MyCommFun.RequestOpenid();
                this.shopid = MyCommFun.RequestInt("shopid");
                this.indexurl = string.Concat(new object[] { "index.aspx?wid=", base.wid, "&openid=", base.openid });
                this.carturl = string.Concat(new object[] { "cart.aspx?wid=", base.wid, "&openid=", base.openid });
                this.userinfourl = string.Concat(new object[] { "userinfo.aspx?wid=", base.wid, "&openid=", base.openid });
                this.categoryurl = MyCommFun.urlAddOpenid("/shop/category.aspx?wid=" + base.wid, base.openid);
                MxWeiXinPF.Model.users modelByOpenid = new MxWeiXinPF.Model.users();
                MxWeiXinPF.BLL.users users2 = new MxWeiXinPF.BLL.users();
                this.pageSize = 5;
                if (HttpContext.Current.Session["dt_session_user_info"] != null)
                {
                    this.user_info = HttpContext.Current.Session["dt_session_user_info"] as MxWeiXinPF.Model.users;
                    this.uid = this.user_info.id;
                    this.shopid = this.user_info.shopid;
                }
                else
                {
                    modelByOpenid = users2.GetModelByOpenid(base.openid);
                    this.uid = modelByOpenid.id;
                    this.shopid = modelByOpenid.shopid;
                }
                if (!this.Page.IsPostBack)
                {
                    this.RptBind("id>0" + this.CombSqlTxt(this.uid), "updatetime desc");
                }
            }
            catch (Exception ex)
            {

            }

        }

        private void RptBind(string _strWhere, string _orderby)
        {
            this.page = MXRequest.GetQueryInt("page", 1);
            this.rptList.DataSource = new MxWeiXinPF.BLL.userbbs().GetList(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
            this.rptList.DataBind();
            this.txtPageNum.Text = this.pageSize.ToString();
            string linkUrl = Utils.CombUrlTxt("userbbs.aspx", "uid={0}", new string[] { this.uid.ToString() });
            this.PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, linkUrl, 8);
        }

        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());
            MxWeiXinPF.BLL.userbbs userbbs = new MxWeiXinPF.BLL.userbbs();
            if ((e.CommandName == "Del") && userbbs.Delete(id))
            {
                this.RptBind("id>0" + this.CombSqlTxt(this.uid), "updatetime desc");
                this.Page.ClientScript.RegisterStartupScript(this.Page.ClientScript.GetType(), "myscripts", "<script>alert(\"删除成功！\");</script>");
            }
        }

        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int num;
            if (int.TryParse(this.txtPageNum.Text.Trim(), out num) && (num > 0))
            {
                Utils.WriteCookie("userbbs", num.ToString(), 0x3840);
            }
            base.Response.Redirect(Utils.CombUrlTxt("userbbs.aspx", "uid={0}", new string[] { this.uid.ToString() }));
        }


        private bool SendTemplateMsg(string content, Model.userbbs model)
        {
            try
            {
                if (model == null)
                {
                    return false;
                }
                Model.users umodel = new BLL.users().GetModel(model.uid);

                Model.manager mmodel = new BLL.manager().GetModel(this.shopid);
                if (umodel == null || mmodel == null)
                {
                    return false;
                }
                content = string.Concat("你好,你的店铺:", mmodel.real_name, "的客户:", umodel.nick_name, "发表了一条新留言留言内容为:", model.title,",请尽快回复");
                Model.wx_userweixin weixin = new MxWeiXinPF.BLL.wx_userweixin().GetModel(this.wid);
                if (weixin == null)
                {
                    return false;
                }
                if (!AccessTokenContainer.CheckRegistered(weixin.AppId))
                {
                    AccessTokenContainer.Register(weixin.AppId, weixin.AppSecret);
                }

                WxJsonResult ret = Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(weixin.AppId, mmodel.shopclerkid, content);
                if (ret.errcode == 0)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {

            }

            return false;
        }
    }
}